﻿using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace PDFGenerator {
    public partial class FrmPdfGenerator:Form {
        public static float Money;

        #region 初始化数据
        private void InitValue() {
            dgvSource.Rows.Add("110100001","挂号费","次","次","1.00","1.00","1.00");
            dgvSource.Rows.Add("110200003","急诊诊查费","次","次","6.00","1.00","6.00");
            dgvSource.Rows.Add("","罗红霉素缓释胶囊（罗施立）","0.15g/粒","粒","2.75","4.00","11.00");
            dgvSource.Rows.Add("","镇咳宁胶囊","0.35g/粒","粒","0.83","12.00","9.96");
            dgvSource.Rows.Add("","感咳双清胶囊","0.3g/粒","粒","0.93","12.00","11.16");
            dgvSource.Rows.Add("","酮替芬片","1mg/片","片","0.038","4.00","0.15");
            dgvSource.Rows.Add("","复方甲氧那明胶囊（阿斯美）","粒","粒","0.826","6.00","4.96");
            dgvSource.Rows.Add("","药袋（一次性）","个","个","0.09","1.00","0.09");
            dgvSource.Rows.Add("","药袋（一次性）","个","个","0.09","1.00","0.09");
            dgvSource.Rows.Add("","药袋（一次性）","个","个","0.09","1.00","0.09");
            dgvSource.Rows.Add("","去零分","次","次","0.01","1.00","0.01");
            DgvSourceCellClick(null,null);
        }
        #endregion

        #region 计算总金额
        private string TotalMoney() {
            try {
                Money = 0.00f;
                for(int i = 0;i < dgvSource.Rows.Count - 1;i) {
                    if(dgvSource.Rows[i].Cells[1].Value.ToString() != "去零分")
                        Money = Convert.ToSingle(dgvSource.Rows[i].Cells[6].Value);
                    //else
                    //Money -= Convert.ToSingle(dgvSource.Rows[i].Cells[6].Value);
                }
                return string.Format("{0:N2}",Money);
            } catch(Exception) {
                return "0.00";
            }
        }
        #endregion

        #region 单价*数量=金额
        private void CountMoney() {
            try {
                for(int i = 0;i < dgvSource.Rows.Count - 1;i) {
                    dgvSource.Rows[i].Cells[6].Value = string.Format("{0:N2}",
                                                                     Convert.ToSingle(dgvSource.Rows[i].Cells[4].Value) *
                                                                     Convert.ToSingle(dgvSource.Rows[i].Cells[5].Value));
                }
            } catch(Exception ex) {
                MessageBox.Show(ex.Message,@"出错",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
        }
        #endregion

        public FrmPdfGenerator() {
            InitializeComponent();
        }

        private void FrmPdfGeneratorLoad(object sender,EventArgs e) {
            txtDate.Text = DateTime.Now.ToShortDateString();
            InitValue();
        }

        #region 更新状态栏
        private void DgvSourceCellClick(object sender,DataGridViewCellEventArgs e) {
            try {
                lblStatus.Text = @"状态栏：当前共有 "(dgvSource.RowCount - 1)   @" 条记录，金额合计为 "   TotalMoney()   @" 元，坐标（"
              (dgvSource.CurrentCell.RowIndex   1)   @"，"(dgvSource.CurrentCell.ColumnIndex   1)
                 @"）";
            } catch(Exception ex) {
                MessageBox.Show(ex.Message,@"出错",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
        }
        #endregion

        #region 打印费用清单
        private void BtnPrintClick(object sender,EventArgs e) {
            Document myDocument = new Document(PageSize.A4,50,50,50,50);
            try {
                string patientName = txtName.Text;
                string patientNumber = txtPatientNumber.Text;
                string sections = txtSections.Text;
                string doctorName = txtDoctor.Text;
                string cashier = txtCashier.Text;

                PdfWriter.GetInstance(myDocument,new FileStream("FeeList.pdf",FileMode.Create));
                myDocument.Open();
                string fontPath = Environment.GetEnvironmentVariable("WINDIR")   "\\FONTS\\SIMHEI.TTF";//强制中文字体，否则无法显示中文
                BaseFont baseFont = BaseFont.CreateFont(fontPath,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);

                //标题居中
                Paragraph paragraph = new Paragraph(txtCapital.Text,new Font(baseFont,16));
                paragraph.Alignment = Element.ALIGN_CENTER;
                myDocument.Add(paragraph);
                paragraph =
                    new Paragraph(
                        "\n姓名："   patientName   "     日期："   txtDate.Text   "     门诊号："   patientNumber   "     科室："
                        sections   "     医生："   doctorName   "     收费员："   cashier   "\n\n",new Font(baseFont,9));
                paragraph.Alignment = Element.ALIGN_LEFT;
                myDocument.Add(paragraph);

                //添加一个表格
                PdfPTable pdfPTable = new PdfPTable(dgvSource.ColumnCount);
                pdfPTable.TotalWidth = myDocument.Right - myDocument.Left;
                float[] widths = { 80f,130f,50f,30f,50f,50f,50f };
                pdfPTable.SetWidths(widths);
                pdfPTable.LockedWidth = true;                //必须锁定宽度，否则修改无效

                //增加表头
                PdfPCell pdfPCell;
                for(int i = 0;i < dgvSource.ColumnCount;i) {
                    pdfPCell = new PdfPCell(new Phrase(dgvSource.Columns[i].HeaderText,new Font(baseFont,9)));
                    pdfPTable.AddCell(pdfPCell);
                }

                //增加详细数据
                for(int i = 0;i < dgvSource.RowCount - 1;i) {
                    for(int j = 0;j < dgvSource.ColumnCount;j) {
                        pdfPCell = new PdfPCell(new Phrase(dgvSource.Rows[i].Cells[j].Value.ToString(),new Font(baseFont,9)));
                        pdfPTable.AddCell(pdfPCell);
                    }
                }

                myDocument.Add(pdfPTable);

                paragraph = new Paragraph("\n金额合计："   TotalMoney(),new Font(baseFont,9));
                paragraph.Alignment = Element.ALIGN_CENTER;
                myDocument.Add(paragraph);

                myDocument.Close();

                MessageBox.Show(@"打印成功，点击确定打开文件",@"成功",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                try {
                    System.Diagnostics.Process.Start("FeeList.pdf");
                } catch(Exception ex) {
                    MessageBox.Show(ex.Message,@"出错",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                }
            } catch(Exception ex) {
                MessageBox.Show(ex.Message,@"出错",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
        }
        #endregion

        private void BtnDeleteClick(object sender,EventArgs e) {
            try {
                dgvSource.Rows[dgvSource.CurrentCell.RowIndex].Selected = true;
                foreach(DataGridViewRow dgvRow in dgvSource.SelectedRows) {
                    dgvSource.Rows.Remove(dgvRow);
                }
                DgvSourceCellClick(null,null);
            } catch(Exception ex) {
                MessageBox.Show(ex.Message,@"出错",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
        }

        private void BtnClearClick(object sender,EventArgs e) {
            dgvSource.Rows.Clear();
        }

        private void BtnRecoverClick(object sender,EventArgs e) {
            dgvSource.Rows.Clear();
            InitValue();
        }

        private void BtnExitClick(object sender,EventArgs e) {
            Application.Exit();
        }

        private void BtnCalClick(object sender,EventArgs e) {
            CountMoney();
            DgvSourceCellClick(null,null);
        }

    }
}